#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import sys
import json
import time 
from subprocess import Popen, PIPE
from Ump import utils

def mkdir_(dir_):
    if not os.path.exists(dir_):
        p1 = Popen(['mkdir','-p',dir_], stdout=PIPE)
        stdout, stderr = p1.communicate()
        if not p1.returncode == 0:
            print >>sys.stderr, 'Warn: create file error', stderr


def host_iops_(dir_,obj):
    res = os.listdir(dir_)
    lun = []
    res = sorted(res)
    for t in res:
        objs = os.listdir('%s/%s'%(dir_,t))
        if obj not in objs:
            continue

        rf = file('%s/%s/%s'%(dir_,t,obj),'r')
        rfile = rf.readlines()
        rfile_list = [float(data.strip('\n').split(':')[-1])\
                for data in rfile if data.strip('\n').strip('\x00\n')]
        lun.append(rfile_list)
        rf.close()

    rid,wid,rbid,wbid,tid = range(5)
    read_,write_,iops_,out_,in_,speed_ = [],[],[],[],[],[] 
    times = []
    if len(lun) == 0:
        return 0,0,0,0,0,0,[]

    for i in range(len(lun)-1) : 
        tail= lun[i]
        next_tail = lun[i+1]
        difftime  = next_tail[4] - tail[4] 
        if next_tail[0] - tail[0] < 0:
            continue
        read  = (next_tail[0] - tail[0]) / difftime
        write = (next_tail[1] - tail[1]) / difftime
        out   = (next_tail[2] - tail[2]) / difftime /1024/1024
        inx   = (next_tail[3] - tail[3]) / difftime /1024/1024
        iops  = read + write
        speed = out + inx
        read_.append(read)
        write_.append(write)
        out_.append(out)
        in_.append(inx)
        iops_.append(iops)
        speed_.append(speed)
        times.append(next_tail[4])
    if len(in_) == 0:
        return 0,0,0,0,0,0,times

    return sum(iops_) / len(iops_),\
        sum(read_) / len(read_),\
        sum(write_) / len(write_),\
        sum(in_) / len(in_),\
        sum(out_) / len(out_),\
        sum(speed_) / len(speed_),\
        times

_home = '%s/tmp/ump' % (utils.install_path)
mkdir_(_home+'/IO')
def volume_iops(volume):
    avg_in    = 0 
    avg_out   = 0 
    avg_iops  = 0 
    avg_read  = 0 
    avg_write = 0 
    avg_speed = 0 
    obj = volume.chunkid
    all_times = []
    for host in volume.cluster.hosts:
        host_io_path = '%s/host/%s' % (_home, host.name)
        mkdir_(host_io_path)
        dirs = os.listdir(host_io_path)
        if len(dirs) == 0:
            continue
        dir_ = sorted(dirs)[-1]
        dir_ = '%s/host/%s/%s'%(_home,host.name,dir_)
        avg_iops_,avg_read_,avg_write_,\
            avg_in_,avg_out_,avg_speed_,times = host_iops_(dir_,obj)
        avg_in    += avg_in_ 
        avg_out   += avg_out_ 
        avg_speed += avg_speed_ 
        avg_iops  += avg_iops_ 
        avg_read  += avg_read_ 
        avg_write += avg_write_ 
        all_times.extend(times)
    timestamp = time.time()
    if not all_times == []:
        timestamp = max(all_times)
    avg_iops = int(avg_read) + int(avg_write)
    avg_speed = int(avg_in) + int(avg_out)

    return int(avg_iops), int(avg_read), int(avg_write),\
            int(avg_speed), int(avg_in), int(avg_out),\
           timestamp


if __name__ == '__main__':
    host_iops_('/root/io.1387344931/','6.1387178925.object')
